package com.example.kingdee.sqlTool.block;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.example.kingdee.common.KCloudResult;
import com.example.kingdee.exception.ProcedureException;
import com.example.kingdee.sqlTool.common.ConditionMap;
import com.example.kingdee.sqlTool.common.OrderMap;
import com.example.kingdee.sqlTool.common.QueryResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sqlTool的积木类,里面包含了sqltool的底层查询方法，根据实际情况也可以直接调用
 */
@Service
public class SqlToolBlock {

    private ArrayList<HashMap<String,Object>> dataMap;




    /**
     * 解析selectArray为selectSql
     * @param selectArray
     * @return
     */
    public String getSelectSqlBySelectArray(ArrayList<String> selectArray){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < selectArray.size(); i++) {
            if(i!=selectArray.size()-1){
                sb.append(selectArray.get(i)).append(",");
            }else if (i == selectArray.size()-1) {
                sb.append(selectArray.get(i));
            }
        }
        return sb.toString();
    };

    /**
     * 解析condition为whereSql
     * @param condition
     * @return
     */
    public String getWhereSqlByCondition(ConditionMap condition) {
        StringBuffer sb = new StringBuffer();
        AtomicInteger i = new AtomicInteger(1);
        condition.forEach((k,v)->{
            if(!"".equals(v)){
                if(i.get() > 1) {
                    sb.append(" and");
                }
                if(v==null){
                    throw new ProcedureException("系统内部错误:"+k+"为null,请检查代码");
                }
                sb.append(getConditionSqlByKV(k,v));
                i.getAndIncrement();
            }
        });
        String whereSql = "";
        if(sb.length()>0){
            whereSql = " " + sb;
        }else{
            whereSql = sb.toString();
        }
        return whereSql;
    }

    public String getConditionSqlByKV(String k,Object v){
        StringBuffer sb = new StringBuffer();
        sb.append(" ");
        String[] kArray = k.split("@");
        if(kArray.length>1){
            String column = kArray[0];
            String operation = kArray[1];
            switch (operation){
                case "like": sb.append(column).append(" like ").append("'%").append(v).append("%'"); break;
                case ">" : sb.append(column).append(" > ").append("'").append(v).append("'"); break;
                case "<": sb.append(column).append(" < ").append("'").append(v).append("'"); break;
                case "in": sb.append(column).append(" in ").append(getInSql(v)); break;
                case "<>": sb.append(column).append(" <> ").append("'").append(v).append("'"); break;
                case "not_null": sb.append("(").append(column).append(" is not null and ").append(column).append(" <> '')");
                case "likes": {
                    List<String> values = objToList(v);
                    sb.append("(");
                    for (int i = 0; i < values.size(); i++) {
                        String value = values.get(i);
                        String[] split = value.split("#");
                        sb.append(split[0]).append(" like ").append("'%").append(split[1]).append("%'");
                        if (i != values.size() - 1){
                            sb.append(" or ");
                        }
                    }
                    sb.append(")");
                }
                break;
                default:
                    throw new IllegalStateException("Unexpected value: " + operation);
            }
        }else{
            sb.append(k).append(" = ").append("'").append(v).append("'");
        }
        return sb.toString();
    };

    /**
     * 将obj转为list
     * @param obj
     * @return
     */
    public List<String> objToList(Object obj){
        List<String> result = new ArrayList<>();
        if (obj instanceof ArrayList<?>) {
            for (Object o : (List<?>) obj) {
                result.add((String) o);
            }
        }
        return result;
    }

    private String getInSql(Object v){
        List<Object> ids = (List<Object>)v;
        if (ids.get(0) instanceof String){
            StringBuilder result = new StringBuilder();
            result.append("(");
            for (int i = 0; i < ids.size(); i++) {
                if (i == ids.size() - 1){
                    result.append("'").append(ids.get(i)).append("'");
                }else {
                    result.append("'").append(ids.get(i)).append("'").append(",");
                }
            }
            result.append(")");
            return result.toString();
        }else {
            StringBuilder result = new StringBuilder();
            result.append("(");
            for (int i = 0; i < ids.size(); i++) {
                if (i == ids.size() - 1){
                    result.append(ids.get(i));
                }else {
                    result.append(ids.get(i)).append(",");
                }
            }
            result.append(")");
            return result.toString();
        }
    }

    /**
     * 解析order为orderSql
     * @param order
     * @return
     */
    public String getOrderSqlByCondition(OrderMap order) {
        StringBuffer sb = new StringBuffer();
        sb.append(" order by");
        AtomicInteger i = new AtomicInteger(1);
        order.forEach((k,v)->{
            sb.append(" ").append(tfToXhx(k)).append(" ").append(v);
            if(i.get() < order.size()) {
                sb.append(",");
            }
            i.getAndIncrement();
        });
        return sb.toString();
    }

    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public String xhxToTf(String str){
        if(str.contains("_")) {
            str = str.toLowerCase();
            Pattern compile = Pattern.compile("_[a-z]");
            Matcher matcher = compile.matcher(str);
            StringBuffer sb = new StringBuffer();
            while (matcher.find()) {
                matcher.appendReplacement(sb, matcher.group(0).toUpperCase().replace("_", ""));
            }
            matcher.appendTail(sb);
            return sb.toString();
        }
        return str;
    }

    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public String tfToXhx(String str){
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(sb,"_"+matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 对报表查询返回结果进行处理
     */
    public void initReportQueryResult(ArrayList<String> selectArray, String resultJson, QueryResult queryResult) {
        System.out.println(resultJson);
        JSONObject jsonObject = JSON.parseObject(resultJson);
        System.out.println(jsonObject);
        JSONObject result = (JSONObject)jsonObject.get("Result");
        Boolean isSuccess = (Boolean)result.get("IsSuccess");
        if (isSuccess != null){
            if (isSuccess){
                JSONArray rows = (JSONArray)result.get("Rows");
                ArrayList<HashMap<String, Object>> records = new ArrayList<>();
                for (Object row : rows) {
                    JSONArray arrayRow = (JSONArray)row;
                    HashMap<String, Object> resultRow = new HashMap<>();
                    for (int i = 0; i < selectArray.size(); i++) {
                        resultRow.put(selectArray.get(i), arrayRow.get(i));
                    }
                    records.add(resultRow);
                }
                queryResult.setCode("200");
                queryResult.setMsg("查询成功");
                queryResult.setRecords(records);
                queryResult.setSelectArray(selectArray);
            }
        }else {
            //表示请求失败
            JSONObject errorResponse = (JSONObject)result.get("ResponseStatus");
            JSONArray errors = (JSONArray)errorResponse.get("Errors");
            JSONObject error = (JSONObject)errors.get(0);
            String message = error.get("Message").toString();
            queryResult.setCode("500");
            queryResult.setMsg(message);
        }

    }

    /**
     * 对返回结果进行处理
     */
    public void initQueryResult(ArrayList<String> selectArray, List<List<Object>> result, QueryResult queryResult){
        if (result.size() != 0){
            if (result.get(0).get(0) instanceof Map){
                Map<String, Object> resultMap = (Map<String, Object>)result.get(0).get(0);
                Map<String, Object> statusMap = (Map<String, Object>) resultMap.get("Result");
                String resultJson = JSONArray.toJSONString(statusMap.get("ResponseStatus"));
                KCloudResult kCloudResult = JSON.parseObject(resultJson, new TypeReference<KCloudResult>(){});
                Map<String, Object> errors = kCloudResult.Errors.get(0);
                queryResult.setCode("500");
                queryResult.setMsg(errors.get("Message").toString());
            }else {
                ArrayList<HashMap<String, Object>> records = new ArrayList<>();
                for (List<Object> record : result) {
                    HashMap<String, Object> row = new HashMap<>();
                    for (int i = 0; i < selectArray.size(); i++) {
                        row.put(selectArray.get(i), record.get(i));
                    }
                    records.add(row);
                }
                queryResult.setCode("200");
                queryResult.setMsg("查询成功");
                queryResult.setRecords(records);
                queryResult.setSelectArray(selectArray);
            }
        }else {
            queryResult.setCode("200");
            queryResult.setMsg("查询成功");
            queryResult.setRecords(new ArrayList<>());
            queryResult.setSelectArray(selectArray);
        }
    }

    /**
     * 转换notes数据结构
     * @param sqlResult
     * @return
     */
    public HashMap<String,String> initNotes(ArrayList<HashMap<String,String>> sqlResult){
        HashMap<String,String> notes = new HashMap<>();
        for (HashMap<String, String> map : sqlResult) {
            StringBuilder columnName = new StringBuilder();
            StringBuilder columnComment = new StringBuilder();
            map.forEach((k,v)->{
//                switch (k) {
//                    case "column_name" ->columnName.append(xhxToTf(v));
//                    case "column_comment" ->columnComment.append(v);
//                }
            });
            notes.put(columnName.toString(),columnComment.toString());
        }
        return notes;
    };

}
